const WebSocket = require('ws');
const {runBat} = require("./batServer");
const {runPython} = require("./pythonServer");



module.exports = {
  createWS: ()=> {
    const wss = new WebSocket.Server({ port: 8765 });
    global.bat = null
    wss.on('connection', function connection(ws) {
      console.log('WebSocket connected');

      ws.on('message', (message) => {
        // 必须要toString()
        message = JSON.parse(message.toString())
        const {cmd, data} = message
        console.log('received: %s', JSON.stringify(message));
        // 处理收到的消息
        // 例如，将消息发送给渲染进程
        switch (cmd){
          case "start":
            // 开始训练
            global.bat = runBat(data)
            break
          case 'close':
            // 结束训练
            global.bat.stdin.write('1\n');
            break
          case 'py:TargetCreateDemo':
            runPython('TargetCreateDemo', data)
            break
          default:
            console.log(`ws message: ${message}`)
        }
      });

      ws.on('close', function close() {
        console.log('WebSocket disconnected');
      });
    });
  }
}


